import React, { useMemo, useState } from "react";
import { NavBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import {
  ShareSheet,
  ProductCard,
  Stepper,
  Checkbox,
  SubmitBar,
} from "react-vant";
import { SendOutline } from "antd-mobile-icons";
// 假设购物车商品项的类型定义
interface CartItem {
  restorativesid: string;
  restorativesname: string;
  restorativesprice: number;
  restorativesdesc: string;
  restorativesimage: string;
  count: number;
  status: boolean;
}
// 从 cartSlice 引入相关的 action creators
import { dan, quan, numchange, alldel } from "../../store/cartSlice";
import { useAppDispatch, useAppSelector } from "../../store/store";
import style from "./index.module.css";

const Index: React.FC = () => {
  const navigate = useNavigate();
  // 用于记录已选中商品的 ids，初始为空数组
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [isEditMode, setIsEditMode] = useState(false);
  const [visible, setVisible] = useState(false);
  const dispath = useAppDispatch();
  // 从 Redux store 中获取购物车商品列表
  const { cartlist } = useAppSelector((state) => state.cartSlice);

  // 计算全选状态，使用 useMemo 避免不必要的重复计算
  const allchecked = useMemo(() => {
    if (cartlist.length === 0) {
      return false;
    }
    return cartlist.every((item: CartItem) => item.status);
  }, [cartlist]);

  // 计算购物车商品总价，使用 useMemo 避免不必要的重复计算
  const total = useMemo(() => {
    return cartlist.reduce((cur: number, item: CartItem) => {
      return item.status ? cur + item.restorativesprice * item.count : cur;
    }, 0);
  }, [cartlist]);

  const options = [
    { name: "微信", icon: "wechat" },
    { name: "朋友圈", icon: "wechat-moments" },
    { name: "QQ", icon: "qq" },
  ];

  const handok = () => {
    localStorage.setItem("allprice", `${total * 100}`);
    navigate("/order", { state: { totalprice: total * 100 } });
  };
  return (
    <div>
      <NavBar
        onBack={() => navigate(-1)}
        style={{ background: "#fff" }}
        right={
          <SendOutline onClick={() => setVisible(true)} fontSize={"25px"} />
        }
      >
        妙手医生_购物车_医患...
      </NavBar>
      {/* 分享面板 */}
      <ShareSheet
        visible={visible}
        options={options}
        title="立即分享给好友"
        onCancel={() => setVisible(false)}
        onSelect={(option, index) => {
          console.log("option", option);
          console.log("index", index);
          setVisible(false);
        }}
      />
      <div
        style={{
          display: "flex",
          height: "35px",
          background: "#fff",
          lineHeight: "26px",
          textAlign: "center",
          fontWeight: "bold",
        }}
      >
        <div style={{ margin: "0 auto" }}>商品清单</div>
        <div
          style={{ marginRight: "8px" }}
          onClick={() => setIsEditMode(!isEditMode)}
        >
          {isEditMode ? "全选" : "编辑"}
        </div>
      </div>
      <div>
        {cartlist.map((item: CartItem) => {
          return (
            <div key={item.restorativesid}>
              <ProductCard
                num={item.count}
                price={item.restorativesprice}
                desc={item.restorativesdesc}
                title={item.restorativesname}
                thumb={
                  <Checkbox
                    checked={isEditMode ? item.status : item.status}
                    onChange={() => {
                      if (isEditMode) {
                        // 在编辑模式下，更新单个商品的选中状态，并相应更新 selectedItems 数组
                        const newStatus = !item.status;
                        dispath(
                          dan({
                            restorativesid: item.restorativesid,
                            status: newStatus,
                          })
                        );
                        if (newStatus) {
                          setSelectedItems([
                            ...selectedItems,
                            item.restorativesid,
                          ]);
                        } else {
                          setSelectedItems(
                            selectedItems.filter(
                              (id) => id !== item.restorativesid
                            )
                          );
                        }
                      } else {
                        // 非编辑模式下，仅更新单个商品的选中状态
                        dispath(dan({ restorativesid: item.restorativesid }));
                      }
                    }}
                  >
                    <img
                      src={item.restorativesimage}
                      style={{ width: "60px", height: "60px" }}
                      alt=""
                    />
                  </Checkbox>
                }
                footer={
                  <Stepper
                    min={0}
                    value={item.count}
                    onChange={(v) =>
                      dispath(
                        numchange({
                          restorativesid: item.restorativesid,
                          count: v,
                        })
                      )
                    }
                  />
                }
              />
            </div>
          );
        })}
      </div>
      <div>
        <SubmitBar
          price={isEditMode ? 0 : total * 100}
          buttonText={isEditMode ? "删除" : "确定"}
          onSubmit={() => handok()}
        >
          <Checkbox
            checked={
              isEditMode
                ? cartlist.every((item: CartItem) => item.status)
                : allchecked
            }
            onChange={() => {
              if (isEditMode) {
                // 在编辑模式下，更新所有商品的选中状态
                const newStatus = !cartlist.every(
                  (item: CartItem) => item.status
                );
                cartlist.forEach((item: CartItem) => {
                  dispath(
                    dan({
                      restorativesid: item.restorativesid,
                      status: newStatus,
                    })
                  );
                });
                // 根据全选结果更新 selectedItems 数组
                if (newStatus) {
                  const allSelectedIds = cartlist.map(
                    (item: CartItem) => item.restorativesid
                  );
                  setSelectedItems(allSelectedIds);
                } else {
                  setSelectedItems([]);
                }
              } else {
                // 非编辑模式下，执行全选或取消全选操作
                dispath(quan(!allchecked));
              }
            }}
          >
            {isEditMode ? "全选" : "全选"}
          </Checkbox>
          {isEditMode && (
            <button
              style={{
                border: "none",
                background: "none",
                color: "red",
                marginLeft: "20px",
              }}
              onClick={() => {
                // 点击删除按钮，调用 alldel action 批量删除已选中的商品，并清空 selectedItems 数组
                dispath(alldel({ restorativesids: selectedItems }));
                setSelectedItems([]);
              }}
            >
              删除
            </button>
          )}
        </SubmitBar>
      </div>
    </div>
  );
};

export default Index;
